<template>
  <div class="upload-file">
    <div class="upload-wrap" v-loading="loading">
      <div class="upload-text">
        <a target="_blank" href="/image/policy_template.xlsx"><img src="../../assets/upload/excel.jpg" alt=""></a>
        <div class="upload-warning">请按照模板文件上传数据，否则可能造成校验失败！</div>
      </div>
      <div class="button-up">
        <el-upload
          class="upload-demo"
          :action="url+'/policy/upload'"
          :http-request="uploadFile"
          :before-remove="beforeRemove"
          multiple
          :file-list="fileList">
          <el-button size="mini">上传</el-button>
        </el-upload>
        <div class="import-in">
          <el-button size="mini" @click="importFile" :disabled="isImport">导入</el-button>
        </div>

      </div>

    </div>
  </div>
</template>

<script>
  import {uploadFile, importFile} from "@/api/upload";

  export default {
    data() {
      return {
        fileList: [],
        fileId: '',
        loading: false,
        isImport: true,
        url: process.env.VUE_APP_BASE_API
      }
    },
    created() {

    },
    methods: {
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      uploadFile(data) {
        this.loading = true;
        let formData = new FormData();
        formData.append('file', data.file);
        uploadFile(formData).then(res => {
          this.fileId = res.result.id;
          this.loading = false;
          this.isImport = false;
        }).catch(error => {
          this.loading = false;

        })
      },
      importFile() {
        this.loading = true;
        this.isImport = true;
        importFile({id: this.fileId}).then(res => {
          this.loading = false;
          this.$message({
            showClose: true,
            message: '导入成功',
            type: 'success'
          });
        }).catch(error=>{
          this.loading = false;

        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .upload-file {
    .upload-wrap {
      width: 50%;
      margin: auto;
      /*background: lightgray;*/
      margin-top: 24px;
      padding: 24px;

      .upload-text {
        display: flex;

        img {
          width: 50px;
          height: 50px;
          margin-right: 12px;
        }

        .upload-warning {
          color: red;
          width: 200px;
        }
      }

      .button-up {
        margin-top: 12px;
        display: flex;
        justify-content: flex-end;

        .import-in {

        }
      }
    }
  }
</style>
